<template>
  <div class="employee-container">
    <!-- 顶部操作栏 -->
    <div class="operation-bar">
      <el-button type="primary" @click="handleAdd" :icon="Plus">新增员工</el-button>
      <el-input
        v-model="searchKey"
        placeholder="搜索员工姓名/工号"
        class="search-input"
        :prefix-icon="Search"
        clearable
      />
    </div>

    <!-- 员工列表 -->
    <el-card class="table-card" :body-style="{ padding: '0px' }" v-loading="loading">
      <el-tabs v-model="activeTab" class="custom-tabs">
        <el-tab-pane label="所有员工" name="all">
          <el-table 
            :data="paginatedEmployeeList" 
            style="width: 100%"
            :header-cell-style="{ background: '#f5f7fa' }"
            border>
            <el-table-column prop="employeeId" label="员工ID" min-width="80" align="center" />
            <el-table-column prop="name" label="姓名" min-width="100" align="center" />
            <el-table-column prop="idCardNumber" label="身份证号" min-width="180" align="center" />
            <el-table-column prop="branchName" label="所属公司" min-width="120" align="center" />
            <el-table-column prop="empType" label="员工类型" min-width="100" align="center">
              <template #default="scope">
                <el-tag :type="scope.row.empType === '导游' ? 'success' : 'info'">
                  {{ scope.row.empType }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="guideNumber" label="导游号" min-width="100" align="center" />
            <el-table-column prop="guideLevel" label="导游等级" min-width="100" align="center">
              <template #default="scope">
                <el-tag v-if="scope.row.guideLevel" type="warning">
                  Level {{ scope.row.guideLevel }}
                </el-tag>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" min-width="80" fixed="right" align="center">
              <template #default="scope">
                <el-button type="danger" link @click="handleDelete(scope.row)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[10, 20, 50, 100]"
              :total="filteredEmployeeList.length"
              layout="total, sizes, prev, pager, next"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-tab-pane>

        <el-tab-pane label="导游信息" name="guide">
          <el-table 
            :data="paginatedGuideList" 
            style="width: 100%"
            :header-cell-style="{ background: '#f5f7fa' }"
            border>
            <el-table-column prop="employeeId" label="员工ID" width="100" align="center" />
            <el-table-column prop="guideId" label="导游ID" width="100" align="center" />
            <el-table-column prop="name" label="姓名" width="120" align="center" />
            <el-table-column prop="idCardNumber" label="身份证号" width="180" align="center" />
            <el-table-column prop="branchName" label="所属公司" width="150" align="center" />
            <el-table-column prop="empType" label="员工类型" width="120" align="center">
              <template #default="scope">
                <el-tag type="success">{{ scope.row.empType }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="guideNumber" label="导游号" width="120" align="center" />
            <el-table-column prop="guideLevel" label="导游等级" width="120" align="center">
              <template #default="scope">
                <el-tag type="warning">Level {{ scope.row.guideLevel }}</el-tag>
              </template>
            </el-table-column>
          </el-table>
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="currentGuidePage"
              v-model:page-size="guidePageSize"
              :page-sizes="[10, 20, 50, 100]"
              :total="guideList.length"
              layout="total, sizes, prev, pager, next"
              @size-change="handleGuideSizeChange"
              @current-change="handleGuideCurrentChange"
            />
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 新增员工对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="新增员工"
      width="500px"
      :close-on-click-modal="false"
      destroy-on-close>
      <el-form
        ref="formRef"
        :model="employeeForm"
        :rules="rules"
        label-width="100px"
        class="custom-form">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="employeeForm.name" placeholder="请输入员工姓名" />
        </el-form-item>
        <el-form-item label="身份证号" prop="idCardNumber">
          <el-input v-model="employeeForm.idCardNumber" placeholder="请输入身份证号" />
        </el-form-item>
        <el-form-item label="所属分公司" prop="branchId">
          <el-select 
            v-model="employeeForm.branchId" 
            placeholder="请选择分公司"
            class="full-width">
            <el-option
              v-for="branch in branchOptions"
              :key="branch.branchId"
              :label="branch.branchName"
              :value="branch.branchId" />
          </el-select>
        </el-form-item>
        <el-form-item label="员工类型" prop="empTyId">
          <el-select 
            v-model="employeeForm.empTyId" 
            placeholder="请选择员工类型"
            class="full-width">
            <el-option
              v-for="type in employeeTypeOptions"
              :key="type.empTyId"
              :label="type.job"
              :value="type.empTyId" />
          </el-select>
        </el-form-item>
        <el-form-item 
          label="导游号" 
          prop="guideNumber"
          v-if="employeeForm.empTyId === 2">
          <el-input v-model="employeeForm.guideNumber" placeholder="请输入导游编号" />
        </el-form-item>
        <el-form-item 
          label="导游等级" 
          prop="guideLevel"
          v-if="employeeForm.empTyId === 2">
          <el-select 
            v-model="employeeForm.guideLevel" 
            placeholder="请选择导游等级"
            class="full-width">
            <el-option :value="1" label="Level 1" />
            <el-option :value="2" label="Level 2" />
            <el-option :value="3" label="Level 3" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { Plus, Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { employeeApi } from '@/api/modules/employee'

// 数据定义
const activeTab = ref('all')
const employeeList = ref([])
const guideList = ref([])
const dialogVisible = ref(false)
const formRef = ref<FormInstance>()
const searchKey = ref('')
const branchOptions = ref([])
const employeeTypeOptions = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const currentGuidePage = ref(1)
const guidePageSize = ref(10)
const loading = ref(false)

// 表单数据
const employeeForm = ref({
  name: '',
  idCardNumber: '',
  branchId: undefined,
  empTyId: undefined,
  guideNumber: '',
  guideLevel: undefined
})

// 表单校验规则
const rules = ref<FormRules>({
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  idCardNumber: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入正确的身份证号', trigger: 'blur' }
  ],
  branchId: [{ required: true, message: '请选择所属分公司', trigger: 'change' }],
  empTyId: [{ required: true, message: '请选择员工类型', trigger: 'change' }],
  guideNumber: [
    { required: true, message: '请输入导游号', trigger: 'blur' }
  ],
  guideLevel: [
    { required: true, message: '请选择导游等级', trigger: 'change' }
  ]
})

// 搜索过滤
const filteredEmployeeList = computed(() => {
  if (!searchKey.value) return employeeList.value
  return employeeList.value.filter(item => 
    item.name.includes(searchKey.value) || 
    String(item.employeeId).includes(searchKey.value)
  )
})

// 添加计算属性来处理分页数据
const paginatedEmployeeList = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredEmployeeList.value.slice(start, end)
})

const paginatedGuideList = computed(() => {
  const start = (currentGuidePage.value - 1) * guidePageSize.value
  const end = start + guidePageSize.value
  return guideList.value.slice(start, end)
})

// 获取选项数据
const fetchOptions = async () => {
  loading.value = true
  try {
    const [branchRes, typeRes] = await Promise.all([
      employeeApi.getAllBranches(),
      employeeApi.getEmployeeTypes()
    ])
    branchOptions.value = branchRes??[]
    employeeTypeOptions.value = typeRes??[]
  } catch (error) {
    ElMessage.error('获取选项数据失败')
  } finally {
    loading.value = false
  }
}

// 获取员工数据
const fetchData = async () => {
  loading.value = true
  try {
    const [employeeRes, guideRes] = await Promise.all([
      employeeApi.getAllEmployees(),
      employeeApi.getAllGuides()
    ])
    employeeList.value = employeeRes??[]
    guideList.value = guideRes??[]
  } catch (error) {
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 新增员工
const handleAdd = () => {
  employeeForm.value = {
    name: '',
    idCardNumber: '',
    branchId: undefined,
    empTyId: undefined,
    guideNumber: '',
    guideLevel: undefined
  }
  dialogVisible.value = true
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await employeeApi.addEmployee(employeeForm.value)
        ElMessage.success('添加成功')
        dialogVisible.value = false
        fetchData()
      } catch (error) {
        ElMessage.error('添加失败')
      }
    }
  })
}

// 删除员工
const handleDelete = (row: any) => {
  ElMessageBox.confirm(
    '确定要删除该员工吗？此操作不可恢复',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await employeeApi.deleteEmployee(row.employeeId)
      ElMessage.success('删除成功')
      fetchData()
    } catch (error) {
      ElMessage.error('删除失败')
    }
  })
}

// 添加分页处理方法
const handleCurrentChange = (val: number) => {
  currentPage.value = val
}

const handleSizeChange = (val: number) => {
  pageSize.value = val
  currentPage.value = 1
}

const handleGuideCurrentChange = (val: number) => {
  currentGuidePage.value = val
}

const handleGuideSizeChange = (val: number) => {
  guidePageSize.value = val
  currentGuidePage.value = 1
}

onMounted(() => {
  fetchData()
  fetchOptions()
})
</script>

<style scoped>
.employee-container {
  padding: 20px;
  background-color: #f0f2f5;
  min-height: calc(100vh - 84px);
  padding-bottom: 100px;
}

.operation-bar {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-input {
  width: 300px;
}

.table-card {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0,21,41,.08);
  padding: 0 20px;
}

.custom-tabs {
  padding: 20px 20px 0;
}

.custom-form {
  padding: 20px;
}

.full-width {
  width: 100%;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding-top: 20px;
}

:deep(.el-table) {
  margin: 20px 0;
  border-radius: 4px;
  overflow: hidden;
}

:deep(.el-table__header) {
  width: 100% !important;
}

:deep(.el-table__body) {
  width: 100% !important;
}

:deep(.el-table__cell) {
  text-align: center;
  .cell {
    white-space: nowrap;
  }
}

:deep(.el-table__inner-wrapper) {
  padding: 0 !important;
}

:deep(.el-table th) {
  font-weight: 600;
}

:deep(.el-dialog__body) {
  padding: 0;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-input__inner) {
  border-radius: 4px;
}

:deep(.el-select) {
  width: 100%;
}

.pagination-container {
  padding: 20px;
  margin-bottom: 40px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-pagination) {
  padding: 0;
  margin: 0;
}
</style> 